package com.tsfyun.scm.controller.file;

import cn.hutool.core.io.FileUtil;
import com.tsfyun.common.base.controller.BaseController;
import com.tsfyun.common.base.dto.ExportExcelFileDTO;
import com.tsfyun.common.base.dto.Result;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.TsfPreconditions;
import com.tsfyun.scm.entity.file.ExportFile;
import com.tsfyun.scm.service.file.IExportFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 导出文件
 */
@Slf4j
@RestController
@RequestMapping(value = "/export")
public class ExportController extends BaseController {

    @Autowired
    private IExportFileService exportService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 导出
     * @param id
     * @param request
     * @param response
     */
    @GetMapping(value = "/down")
    public void down(@RequestParam(value = "id") Long id, HttpServletRequest request, HttpServletResponse response){
        OutputStream outputStream = null;
        try{
            ExportFile exportFile = exportService.getById(id);
            TsfPreconditions.checkArgument(Objects.nonNull(exportFile),new ServiceException("导出记录不存在"));
            File file = new File(exportFile.getPath());
            if(null != file && file.exists()){
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(exportFile.getFileName(), "UTF-8"));
                outputStream = response.getOutputStream();
                FileUtil.writeToStream(file,outputStream);
                outputStream.flush();
                //读取一次删除
                if(exportFile.getOnce()){
                     //启动子线程删除文件
                    threadPoolTaskExecutor.execute(()-> exportService.removeExportFile(id,exportFile.getPath()));
                }
            }
        } catch (Exception e){
            log.error("导出文件异常",e);
        } finally {
            if(Objects.nonNull(outputStream)) {
                IOUtils.closeQuietly(outputStream);
            }
        }
    }

    /**
     * 保存文件导出
     * @param dto
     * @return
     */
    @PostMapping(value = "/saveExcelFile")
    public Result<Long> saveExcelFile(@RequestBody @Validated ExportExcelFileDTO dto) throws Exception {
        return success(exportService.exportExcel(dto));
    }

}
